import {
  userCollection,
  ErrorCode
} from '../utils/config'

async function bindEmail ({
  uid,
  email,
  // 不传递code时不验证直接绑定
  code
}) {
  email = email && email.trim()
  if (!email) {
    return {
      code: ErrorCode.PARAM_ERROR,
      msg: '邮箱不可为空'
    }
  }
  const {
    emailToLowerCase
  } = this._getConfig()
  if (emailToLowerCase) {
    email = email.toLowerCase()
  }
  const checkRes = await userCollection.where({
    email,
    email_confirmed: 1
  })
    .limit(1)
    .get()
  if (checkRes && checkRes.data.length > 0) {
    return {
      code: 60201,
      msg: '此邮箱已被绑定'
    }
  }
  if (code) {
    const verifyRes = await this.verifyCode({
      email,
      code,
      type: 'bind'
    })
    if (verifyRes.code !== 0) {
      return verifyRes // 验证失败
    }
  }
  await userCollection.doc(uid).update({
    email,
    email_confirmed: 1
  })

  return {
    code: 0,
    msg: '邮箱绑定成功',
    email
  }
}

export default bindEmail
